package com.leecode.xiehf.page_02;

import com.leecode.Printer;

/**
 * 给你一个正整数 n ，生成一个包含 1 到 n2 所有元素，且元素按顺时针顺序螺旋排列的 n x n 正方形矩阵 matrix
 * https://leetcode-cn.com/problems/spiral-matrix-ii/。
 */
public class Solution_0059 extends Printer {

    public static void main(String[] args) {
        Solution_0059 solution = new Solution_0059();
        int[][] intervals = {{1, 2}, {3, 5}, {6, 7}, {8, 10}, {12, 16}};
//        int[][] intervals = {{1, 5}};
//        int[][] intervals = {{2, 3}, {4, 5}, {6, 7}, {1, 10}};
//        int s = solution.lengthOfLastWord("HelloWorld");
        int[][] s = solution.generateMatrix(4);
        print(s);
    }

    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];
        hor(arr, 0, 0, n, n, true, 1);
        return arr;
    }


    private void hor(int[][] nums, int x, int y, int width, int height, boolean position, int begin) {
        if (width == 0) {
            return;
        }
        if (position) {
            int end = x + width;
            for (int i = x; i < end; i++) {
                nums[y][i] = begin++;
            }
            ver(nums, end - 1, y + 1, width, height - 1, true, begin);
        } else {
            int end = x - width;
            for (int i = x; i > end; i--) {
                nums[y][i] = begin++;
            }
            ver(nums, end + 1, y - 1, width, height - 1, false, begin);
        }
    }

    // 竖直方向
    private void ver(int[][] nums, int x, int y, int width, int height, boolean position, int begin) {
        if (height == 0) {
            return;
        }
        if (position) {
            int end = y + height;
            for (int i = y; i < end; i++) {
                nums[i][x] = begin++;
            }
            hor(nums, x - 1, end - 1, width - 1, height, false, begin);
        } else {
            int end = y - height;
            for (int i = y; i > end; i--) {
                nums[i][x] = begin++;
            }
            hor(nums, x + 1, end + 1, width - 1, height, true, begin);
        }
    }
}
